<script lang="ts" setup>
import { onActivated, ref } from 'vue';
import { $fetch } from '@/settings/utils/fetch';
import useNotification from '@/settings/hooks/notification';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const templates = import.meta.glob('./template/*.vue', {
  eager: true,
  import: 'default',
}) as Record<string, any>;

const loading = ref(false);
const listing = ref<Record<string, any>[]>([]);
const { success } = useNotification();

const refresh = async () => {
  const { isSuccess, data } = await $fetch('/admin/template/getTemplateList', {
    loadingStatus: loading,
  });

  if (isSuccess) {
    listing.value = data.map((item: Record<string, any>) => {
      return {
        ...item,
        tempControl: JSON.parse(item.tempControl),
      }
    });
  }
}

const save = async (item: Record<string, any>) => {
  const { isSuccess } = await $fetch('/admin/template/updateTempByCommunityId', {
    method: 'post',
    data: {
      templateId: item.templateId,
      tempControl: JSON.stringify(item.tempControl),
    },
    loadingStatus: loading,
  });

  if (isSuccess) {
    success(t('settings.notification.success'));
    refresh();
  }
}

onActivated(() => {
  refresh();
});
</script>

<template>
  <OpenPageSection>
    <OpenGeneralCard>
      <ARow :gutter="[20, 20]">
        <ACol :xxl="12" :xl="24" :xs="24" v-for="item in listing" :key="item.templateId">
          <ACard>
            <template #title>
              {{ item.templateName }}{{ `${item.templateUse == 1 ? $t('settings.view.homepage.module') : ''}` }}
            </template>

            <template #extra>
              <AButton type="primary" size="small" :loading="loading" @click="save(item)" v-confirm>
                <template v-if="item.templateUse == 1">{{ $t('settings.view.homepage.edit') }}</template>
                <template v-else>{{ $t('settings.view.homepage.use') }}</template>
              </AButton>
            </template>

            <Component :is="templates[`./template/${item.tempControl.type}.vue`]" v-model="item.tempControl.options" />
          </ACard>
        </ACol>
      </ARow>
    </OpenGeneralCard>
  </OpenPageSection>
</template>

<style lang="scss" scoped>
</style>
